/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.odichy.andfml.sax;

import org.odichy.andfml.domain.Account;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * AndFML, an FMyLife.com client on Google Android platform.
 *
 * @author Odin Liu<odinushuaia@gmail.com>
 *
 * @version 1.0.0
 */
public class AccountHandler extends DefaultHandler {
	private Account account;
	private String error;
	
	private int currentState = 0;
	private final int LOGIN = 1;
	private final int TOKEN = 2;
	private final int CODE = 3;
	private final int PUBDATE = 4;
	private final int ERROR = 5;
	
	@Override
	public void startDocument() throws SAXException {
		account = new Account();
	}
	
	@Override
	public void endDocument()throws SAXException {
		
	}
	
	@Override
	public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
		if("root".equals(localName)) {
			currentState = 0;
			return;
		}
		else if("login".equals(localName)) {
			currentState = LOGIN;
			return;
		}
		else if("token".equals(localName)) {
			currentState = TOKEN;
			return;
		}
		else if("code".equals(localName)) {
			currentState = CODE;
			return;
		}
		else if("pubdate".equals(localName)) {
			currentState = PUBDATE;
			return;
		}
		else if("error".equals(localName)) {
			currentState = ERROR;
			return;
		}
		currentState = 0;
	}
	
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if("error".equals(localName)) {
			account.addError(error);
			return;
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length) {
		String content = new String(ch, start, length);
		switch(currentState) {
		case LOGIN:
			account.setLogin(content);
			currentState = 0;
			break;
		case TOKEN:
			account.setToken(content);
			currentState = 0;
			break;
		case CODE:
			account.setCode(Integer.parseInt(content));
			currentState = 0;
			break;
		case PUBDATE:
			account.setPubdate(content);
			currentState = 0;
			break;
		case ERROR:
			error = content;
			currentState = 0;
			break;
		default:
			return;
		}
	}

	public Account getAccount() {
		return account;
	}
}
